package com.yan.deezer.utils;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

import com.yan.deezer.data.manager.DataManager;

public class AsyncImageSetter extends AsyncTask<String, Void, Bitmap> {
	private static final String TAG = "YAN_DEEZER_ASYNC_IMAGE_SETTER";
	private int imgID;
	private ImageView mImageView;
	private HashMap<Integer, Bitmap> mImageCache;

	public AsyncImageSetter(ImageView view, int id,
			HashMap<Integer, Bitmap> imageCache) {
		imgID = id;
		mImageView = view;
		mImageCache = imageCache;
	}

	@Override
	protected Bitmap doInBackground(String... params) {
		Bitmap b = null;
		try {
			URL url = new URL(params[0]);
			b = BitmapFactory.decodeStream(url.openStream());
		} catch (MalformedURLException e) {
			Debug.debugWarning(TAG, "MalformedURLException : " + params[0]);
			e.printStackTrace();
		} catch (IOException e) {
			Debug.debugWarning(TAG, "IOException : " + params[0]);
			e.printStackTrace();
		}

		DataManager.getInstance().addBitmap(imgID, b, mImageCache);
		return b;
	}

	@Override
	protected void onPostExecute(Bitmap result) {
		if (mImageView == null)
			return;

		else if (mImageView != null && result == null) {

			return;

		}

		if (((Integer) mImageView.getTag()) == imgID) {
			mImageView.setImageBitmap(result);
		}
	}

}
